package client.printing;

import client.common.result.Result;
import client.common.vo.OrderDetailsVO;
import remote.service.ExcelExportService;
import remote.service.OrderService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单查询和导出窗口
 */
public class QueryOrderForm extends JFrame {
    
    private JComboBox<String> yearComboBox;
    private JComboBox<String> monthComboBox;
    private JButton queryButton;
    private JButton exportButton;
    private JTable orderTable;
    private OrderTableModel orderTableModel;
    
    private OrderService orderService = new OrderService() {
    };
    private ExcelExportService excelExportService = new ExcelExportService() {
    };
    
    public QueryOrderForm() {
        setTitle("订单查询与导出");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null); // 居中
        
        initUI();
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            QueryOrderForm form = new QueryOrderForm();
            form.setVisible(true);
        });
    }
    
    /**
     * 初始化界面组件
     */
    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        
        // 上部查询面板
        JPanel queryPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        
        // 年份下拉框
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        queryPanel.add(new JLabel("年份:"), gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        yearComboBox = new JComboBox<>(); // 确保使用一致的变量名
        for (int year = 2024; year <= 2030; year++) { // 从2024到2030年
            yearComboBox.addItem(String.valueOf(year));
        }
        queryPanel.add(yearComboBox, gbc);
        
        
        // 月份下拉框
        gbc.gridx = 2;
        gbc.anchor = GridBagConstraints.EAST;
        queryPanel.add(new JLabel("月份:"), gbc);
        
        gbc.gridx = 3;
        gbc.anchor = GridBagConstraints.WEST;
        monthComboBox = new JComboBox<>();
        for (int month = 1; month <= 12; month++) { // 1到12月
            monthComboBox.addItem(String.format("%02d", month)); // 格式化为两位数
        }
        queryPanel.add(monthComboBox, gbc);
        
        // 查询按钮
        gbc.gridx = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        queryButton = new JButton("查询");
        queryPanel.add(queryButton, gbc);
        
        // 导出按钮
        gbc.gridx = 5;
        exportButton = new JButton("导出到Excel");
        queryPanel.add(exportButton, gbc);
        
        mainPanel.add(queryPanel, BorderLayout.NORTH);
        
        // 订单表格
        orderTableModel = new OrderTableModel();
        orderTable = new JTable(orderTableModel);
        orderTable.setFillsViewportHeight(true);
        JScrollPane tableScrollPane = new JScrollPane(orderTable);
        mainPanel.add(tableScrollPane, BorderLayout.CENTER);
        
        add(mainPanel);
        
        // 按钮事件
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                queryOrders();
            }
        });
        
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportOrders();
            }
        });
    }
    
    /**
     * 查询订单
     */
    private void queryOrders() {
        // 从下拉框获取选中的年份和月份
        String year = (String) yearComboBox.getSelectedItem(); // 获取选中的年份
        String month = (String) monthComboBox.getSelectedItem(); // 获取选中的月份
        
        if (year == null || month == null || year.isEmpty() || month.isEmpty()) {
            JOptionPane.showMessageDialog(this, "年份和月份不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 输入验证已不需要，因为选择的项是通过下拉框提供的，确保是有效的
        // 使用SwingWorker在后台线程中查询订单
        SwingWorker<Result<List<OrderDetailsVO>>, Void> worker = new SwingWorker<Result<List<OrderDetailsVO>>, Void>() {
            @Override
            protected Result<List<OrderDetailsVO>> doInBackground() throws Exception {
                return orderService.getOrderListByParam(year, month);
            }
            
            @Override
            protected void done() {
                try {
                    Result<List<OrderDetailsVO>> result = get();
                    if (result.getCode() == 200) {
                        List<OrderDetailsVO> orders = result.getData();
                        orderTableModel.setOrders(orders);
                        JOptionPane.showMessageDialog(QueryOrderForm.this, "查询成功，共 " + orders.size() + " 条订单。", "成功", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(QueryOrderForm.this, "查询失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(QueryOrderForm.this, "查询异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 导出订单到Excel
     */
    private void exportOrders() {
        // 从下拉框获取选中的年份和月份
        String year = (String) yearComboBox.getSelectedItem(); // 获取选中的年份
        String month = (String) monthComboBox.getSelectedItem(); // 获取选中的月份
        
        if (year == null || month == null || year.isEmpty() || month.isEmpty()) {
            JOptionPane.showMessageDialog(this, "年份和月份不能为空。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        // 选择保存路径
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存Excel文件");
        int userSelection = fileChooser.showSaveDialog(this);
        if (userSelection != JFileChooser.APPROVE_OPTION) {
            return;
        }
        
        final String savePath = fileChooser.getSelectedFile().getAbsolutePath();
        String correctedSavePath = savePath.toLowerCase().endsWith(".xlsx") ? savePath : savePath + ".xlsx";
        exportToExcel(year, month, correctedSavePath);
    }
    
    /**
     * 辅助方法：执行导出操作
     */
    private void exportToExcel(String year, String month, final String savePath) {
        // 使用SwingWorker在后台线程中导出订单
        SwingWorker<Result<String>, Void> worker = new SwingWorker<Result<String>, Void>() {
            @Override
            protected Result<String> doInBackground() throws Exception {
                return excelExportService.exportOrdersToExcel(year, month, savePath);
            }
            
            @Override
            protected void done() {
                try {
                    Result<String> result = get();
                    if (result.getCode() == 200) {
                        JOptionPane.showMessageDialog(QueryOrderForm.this, "订单导出成功！保存路径: " + savePath, "成功", JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(QueryOrderForm.this, "订单导出失败: " + result.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(QueryOrderForm.this, "导出异常: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        worker.execute();
    }
    
    /**
     * 订单表格模型
     */
    class OrderTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"订单ID", "用户ID", "状态", "提交时间", "出入库状态"};
        private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 定义时间格式
        private List<OrderDetailsVO> orders;
        
        public void setOrders(List<OrderDetailsVO> orders) {
            this.orders = orders;
            fireTableDataChanged();
        }
        
        @Override
        public int getRowCount() {
            return orders == null ? 0 : orders.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            if (orders == null || rowIndex >= orders.size()) {
                return null;
            }
            OrderDetailsVO order = orders.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return order.getOrderId();
                case 1:
                    return order.getUserId();
                case 2:
                    return getStatusDescription(order.getStatus());
                case 3:
                    return formatSubmitTime(order.getSubmitTime()); // 使用格式化方法
                case 4:
                    return getOrderInOutDescription(order.getOrderInOut());
                default:
                    return null;
            }
        }
        
        private String formatSubmitTime(Date submitTime) {
            return submitTime != null ? dateFormat.format(submitTime) : "未知"; // 进行格式化
        }
        
        private String getStatusDescription(int status) {
            switch (status) {
                case 0:
                    return "待处理";
                case 1:
                    return "已完成";
                case 2:
                    return "处理中";
                case 3:
                    return "已取消";
                default:
                    return "未知状态";
            }
        }
        
        private String getOrderInOutDescription(int orderInOut) {
            return orderInOut == 0 ? "出库" : "入库";
        }
    }
}
